package com.easyse.serviceuser.controller;

import com.easyse.common.constants.UserConstant;
import com.easyse.model.DO.User;
import com.easyse.model.vo.ResultVO;
import com.easyse.serviceuser.service.ExitService;
import com.easyse.serviceuser.service.LoginService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@Api(tags = "登录接口")
public class LoginController implements UserConstant {

    @Autowired
    private LoginService loginService;
    @Autowired
    private ExitService exitService;

    @PostMapping(value = "/user/login")
    public ResultVO login( @RequestBody User user){
        //手动校验
        if(
                user.getUsername().isEmpty() ||
                        user.getPassword().isEmpty()
        ){
            return ResultVO.failure("用户名或密码布不能为空！");
        }
        // 登录

        return loginService.doLogin(user);
    }

    @PostMapping(value = "/hello")
    public ResultVO hello(){
        ResultVO resultVO = new ResultVO();
        resultVO.build();
        resultVO = ResultVO.success("你好！");
        return resultVO;
    }

    @PostMapping(value = "/user/register")
    public ResultVO register(@RequestBody User user){
        return loginService.doRegister(user);
    }

    @RequestMapping(value = "/user/out")
    public ResultVO logOut(){
        return exitService.logOut();
    }

    /**
     * 激活用户
     * @param model
     * @param userId
     * @param code 激活码
     * @return
     * http://localhost:8080/echo/activation/用户id/激活码
     */
    @GetMapping("/activation/{userId}/{code}")
    public ResultVO activation(Model model, @PathVariable("userId") Long userId,
                             @PathVariable("code") String code) {
        int result = loginService.activation(userId, code);
        if (result == ACTIVATION_SUCCESS) {
            return ResultVO.success("激活成功, 您的账号已经可以正常使用!");
        }
        else if (result == ACTIVATION_REPEAT) {
            return ResultVO.failure("无效的操作, 您的账号已被激活过!");
        }
        else {
            return ResultVO.failure("激活失败, 您提供的激活码不正确!");
        }
    }

}
